package team.nine.kuaichezuche.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import team.nine.kuaichezuche.model.VehicleInstance;
import team.nine.kuaichezuche.model.VehicleInfo;
import team.nine.kuaichezuche.repository.VehicleInstanceRepository;
import team.nine.kuaichezuche.repository.VehicleInfoRepository;
import team.nine.kuaichezuche.service.VehicleInstanceService;

import java.util.List;

/**
 * 车辆实例服务实现类，实现车辆实例相关的业务逻辑
 */
@Service
public class VehicleInstanceServiceImpl implements VehicleInstanceService {

    @Autowired
    private VehicleInstanceRepository vehicleInstanceRepository;
    
    @Autowired
    private VehicleInfoRepository vehicleInfoRepository;

    /**
     * 创建车辆实例
     */
    @Override
    public VehicleInstance createVehicleInstance(VehicleInstance vehicleInstance) {
        // 这里可以添加验证逻辑，例如检查必填字段
        if (vehicleInstance == null) {
            throw new IllegalArgumentException("车辆实例不能为空");
        }
        if (vehicleInstance.getLicensePlate() == null || vehicleInstance.getLicensePlate().trim().isEmpty()) {
            throw new IllegalArgumentException("车牌号不能为空");
        }
        if (vehicleInstance.getOwner() == null) {
            throw new IllegalArgumentException("车主不能为空");
        }
        if (vehicleInstance.getVehicleInfo() == null) {
            throw new IllegalArgumentException("车辆信息不能为空");
        }
        if (vehicleInstance.getDailyRate() == null) {
            throw new IllegalArgumentException("日租金不能为空");
        }

        // 保存车辆实例到数据库
        return vehicleInstanceRepository.save(vehicleInstance);
    }

    /**
     * 根据ID获取车辆实例
     */
    @Override
    public VehicleInstance getVehicleInstanceById(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("车辆实例ID不能为空");
        }
        return vehicleInstanceRepository.findById(id).orElse(null);
    }

    /**
     * 根据车牌号获取车辆实例
     */
    @Override
    public VehicleInstance getVehicleInstanceByLicensePlate(String licensePlate) {
        if (licensePlate == null || licensePlate.trim().isEmpty()) {
            throw new IllegalArgumentException("车牌号不能为空");
        }
        return vehicleInstanceRepository.findByLicensePlate(licensePlate);
    }

    /**
     * 根据车主ID获取车辆实例列表
     */
    @Override
    public List<VehicleInstance> getVehicleInstancesByOwnerId(Long ownerId) {
        if (ownerId == null) {
            throw new IllegalArgumentException("车主ID不能为空");
        }
        return vehicleInstanceRepository.findByOwnerId(ownerId);
    }

    /**
     * 根据车辆状态获取车辆实例列表
     */
    @Override
    public List<VehicleInstance> getVehicleInstancesByStatus(Byte status) {
        if (status == null) {
            throw new IllegalArgumentException("车辆状态不能为空");
        }
        return vehicleInstanceRepository.findByStatus(status);
    }

    /**
     * 更新车辆实例
     */
    @Override
    public VehicleInstance updateVehicleInstance(VehicleInstance vehicleInstance) {
        if (vehicleInstance == null) {
            throw new IllegalArgumentException("车辆实例不能为空");
        }
        if (vehicleInstance.getId() == null) {
            throw new IllegalArgumentException("车辆实例ID不能为空");
        }

        // 检查车辆实例是否存在
        VehicleInstance existingVehicleInstance = vehicleInstanceRepository.findById(vehicleInstance.getId()).orElse(null);
        if (existingVehicleInstance == null) {
            throw new IllegalArgumentException("车辆实例不存在，ID: " + vehicleInstance.getId());
        }

        // 合并非空字段，避免覆盖为null
        if (vehicleInstance.getLicensePlate() != null) {
            existingVehicleInstance.setLicensePlate(vehicleInstance.getLicensePlate());
        }
        if (vehicleInstance.getMileage() != null) {
            existingVehicleInstance.setMileage(vehicleInstance.getMileage());
        }
        if (vehicleInstance.getRentalCount() != null) {
            existingVehicleInstance.setRentalCount(vehicleInstance.getRentalCount());
        }
        if (vehicleInstance.getAvailableStart() != null) {
            existingVehicleInstance.setAvailableStart(vehicleInstance.getAvailableStart());
        }
        if (vehicleInstance.getAvailableEnd() != null) {
            existingVehicleInstance.setAvailableEnd(vehicleInstance.getAvailableEnd());
        }
        if (vehicleInstance.getOwner() != null) {
            existingVehicleInstance.setOwner(vehicleInstance.getOwner());
        }
        if (vehicleInstance.getVehicleInfo() != null) {
            existingVehicleInstance.setVehicleInfo(vehicleInstance.getVehicleInfo());
        }
        if (vehicleInstance.getDailyRate() != null) {
            existingVehicleInstance.setDailyRate(vehicleInstance.getDailyRate());
        }
        if (vehicleInstance.getNextMaintenance() != null) {
            existingVehicleInstance.setNextMaintenance(vehicleInstance.getNextMaintenance());
        }
        if (vehicleInstance.getInsuranceInfo() != null) {
            existingVehicleInstance.setInsuranceInfo(vehicleInstance.getInsuranceInfo());
        }
        if (vehicleInstance.getStatus() != null) {
            existingVehicleInstance.setStatus(vehicleInstance.getStatus());
        }

        // 保存合并后的车辆实例
        return vehicleInstanceRepository.save(existingVehicleInstance);
    }

    /**
     * 删除车辆实例
     */
    @Override
    public void deleteVehicleInstance(Integer id) {
        if (id == null) {
            throw new IllegalArgumentException("车辆实例ID不能为空");
        }

        // 检查车辆实例是否存在
        VehicleInstance existingVehicleInstance = vehicleInstanceRepository.findById(id).orElse(null);
        if (existingVehicleInstance == null) {
            throw new IllegalArgumentException("车辆实例不存在，ID: " + id);
        }
        
        // 先从车辆实例中获取车辆信息
        VehicleInfo vehicleInfo = existingVehicleInstance.getVehicleInfo();
        
        // 先删除车辆实例表中的记录
        vehicleInstanceRepository.deleteById(id);
        
        // 再删除车辆表中的信息
        vehicleInfoRepository.delete(vehicleInfo);
    }

    /**
     * 根据车辆信息ID获取车辆实例列表
     */
    @Override
    public List<VehicleInstance> getVehicleInstancesByVehicleInfoId(Integer vehicleInfoId) {
        if (vehicleInfoId == null) {
            throw new IllegalArgumentException("车辆信息ID不能为空");
        }
        return vehicleInstanceRepository.findByVehicleInfoId(vehicleInfoId);
    }

    /**
     * 获取车辆实例列表（分页）
     */
    @Override
    public List<VehicleInstance> getVehicleInstanceList(Integer page, Integer pageSize) {
        if (page == null || page < 1) {
            page = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        } else if (pageSize > 10) {
            pageSize = 10; // 限制最多返回10条
        }

        // 创建分页参数
        Pageable pageable = PageRequest.of(page - 1, pageSize);
        
        // 调用repository获取分页结果
        Page<VehicleInstance> vehicleInstancePage = vehicleInstanceRepository.findAll(pageable);
        
        // 返回车辆实例列表
        return vehicleInstancePage.getContent();
    }

    /**
     * 获取车辆实例总数
     */
    @Override
    public int getVehicleInstanceCount() {
        // 调用repository获取车辆实例总数
        return (int) vehicleInstanceRepository.count();
    }
}